import React, { Dispatch, SetStateAction } from 'react';
import { createPortal } from 'react-dom';
import Button, { ButtonType } from '../Button/button';
import classNames from 'classnames';

export type DialogsetVisibleType = Dispatch<SetStateAction<boolean>> | ((value: boolean) => void)

interface DialogProps {
    visible: boolean
    setVisible: DialogsetVisibleType
    // 确认按钮关闭之前的校验
    beforeClose?: Function
    children?: React.ReactNode
    className?: string
    style?: React.CSSProperties
    // title提示文本
    title?: string | number
    // 取消按钮的文本
    cancelText?: string | number
    // 确认按钮的文本
    sureText?: string | number
    // 是否需要遮罩层
    modal?: boolean
    // 点击遮罩层是否可关闭
    modalClose?: boolean
}

const Dialog: React.FC<DialogProps> = (props) => {

    const { children, visible, setVisible, beforeClose, title, cancelText, sureText, className, style, modal, modalClose } = props;

    const handleSure = () => {
        if (beforeClose) {
            beforeClose(() => setVisible(false));
        } else {
            setVisible(false);
        }
    }

    const modalClasses = classNames('yulang-dialog-wrapper', {
        'is-open-model': modal
    })

    const dialogClass = classNames('yulang-dialog-header', className)

    const handleModal = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        // 需要遮罩层的话，需要阻止事件冒泡，防止触发被遮盖住的点击事件触发
        modal && e.preventDefault();
        modalClose && setVisible(false);
    }

    return (<>
        {visible ? createPortal((
            <div className={modalClasses} onClick={(e) => handleModal(e)}>
                <div className={'yulang-dialog-container'} style={style}>
                    <div className={dialogClass}>
                        <div>{title ?? '提示'}</div>
                        <i className={'iconfont icon-guanbi'} onClick={() => setVisible(false)} style={{ 'cursor': 'pointer' }}></i>
                    </div>
                    <div className={'yulang-dialog-body'}>{children}</div>
                    <div className={'yulang-dialog-footer'}>
                        <Button onClick={() => setVisible(false)}>{cancelText ?? '取消'}</Button>
                        <Button btnType={ButtonType.Success} style={{ marginLeft: '5%' }} onClick={handleSure}>{sureText ?? '确定'}</Button>
                    </div>
                </div>
            </div>
        ), document.body) : <></>}
    </>)
}

Dialog.defaultProps = {
    modal: false,
    modalClose: true
}

export default Dialog;